package com.bbm.communitysystem.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.bbm.communitysystem.core.oss.OSS;
import com.bbm.communitysystem.domain.Menu;
import com.bbm.communitysystem.domain.OssFile;
import com.bbm.communitysystem.domain.bo.MenuBo;
import com.bbm.communitysystem.domain.dto.MenuDto;
import com.bbm.communitysystem.mapper.MenuMapper;
import com.bbm.communitysystem.service.IMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author bbm
 * @since 2025-02-18
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

    private final OSS oss;

    @Override
    public MenuDto addMenu(MenuBo menuBo) {

        List<OssFile> ossFiles = oss.saveFile("menu", menuBo.getUpdateBy(), menuBo.getMenuImg());

        Menu menu = BeanUtil.copyProperties(menuBo, Menu.class);

        menu.setMenuImg(ossFiles.get(0).getClientUrl());
        menu.setUpdateTime(System.currentTimeMillis() + "");
        menu.setOssId(ossFiles.get(0).getId());
        log.info("参数：{}", menu);
        boolean save = this.save(menu);


        if (!save) {
            return null;
        }
        return new MenuDto();
    }

    @Override
    public int DeleteMenu(Integer id) {

        Menu byId = getById(id);

        int i = oss.deleteFile(byId.getOssId());

        if (i != 0) {
            return 1;
        }

        boolean b = removeById(id);

        if (!b) {
            return 1;
        }

        return 0;
    }

    @Override
    public MenuDto putMenuImg(MenuBo menuBo) {

        if (menuBo.getMenuImg() == null) {
            return null;
        }

        List<OssFile> menu = oss.saveFile("menu", menuBo.getUpdateBy(), menuBo.getMenuImg());

        if (menu.isEmpty()) {
            return null;
        }

        Menu one = lambdaQuery()
                .eq(Menu::getId, menuBo.getId())
                .one();

        oss.deleteFile(one.getOssId());

        boolean update = lambdaUpdate()
                .eq(Menu::getId, menuBo.getId())
                .set(Menu::getOssId, menu.get(0).getId())
                .set(Menu::getMenuImg, menu.get(0).getClientUrl())

                .set(Menu::getUpdateBy, menuBo.getUpdateBy())
                .set(Menu::getUpdateTime, System.currentTimeMillis())
                .update();

        if (!update) {
            return null;
        }

        return new MenuDto();
    }


}
